NumPy is a data analysis library that supports various linear algebra mathematics. It is important for data science as many libraries in the PyData ecosystem rely on NumPy as one of the main building blocks. It has bindings to C libraries which makes NumPy incredibly fast and memory efficient.
If Anaconda is installed on the system open terminal/Command Prompt and type:
In case Anaconda is not installed on your system open terminal/Command Prompt and type:
Vectors are strictly one dimensional arrays.
Matrices are two dimensional arrays but can have only one row or one column.
To create a one dimensional NumPy array from Python objects, like List:
Create a Python List: >>> my_list = [ 1, 2, 3 ]
Import NumPy: >>> import numpy as np
Cast and assign the array > arr = np.array( my_list )
To create 2 dimensional NumPy arrays from Python List, cast list of list.
Create a Python List >>> my_mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Cast and assign the array > arr = np.array( my_mat )
Link : https://pasteboard.co/IKSQtGM.jpg
To create a NumPy array with built in functions.
[ NOTE: NumPy is imported as np for the whole content ]
1 2 3 4 5 6
>>> np.arange(start, stop, step)β creates a 1 d array >>> np.zeros() - create numpy array with value as 0. >>> np.ones()β create numpy array with values as 1. >>> np.linspace()β creates numpy array with evenly spaced points. >>> np.eye()β creates identity matrix. >>> np.random.rand()β creates a matrix with random numbers.
Link: https://pasteboard.co/IKSRPeR.jpg
Reshaping a NumPy array :
1
2
>>> arr = np.arange(0, 25) # creates a 1 d array with[0, 1, 3β¦ .24] >>>
arr.reshape(5, 5) # converts the 1 d array with 25 values to a 5 x 5 matrix
Link : https://pasteboard.co/IKSSv5f.jpg
Here is the link : https://www.geeksforgeeks.org/numpy-ndarray/ to go through all the NumPy array methods.
Some NumPy Methods
1 2 3 4
>>> arr.copy()β copies the NumPy array >>> arr.max(axis = value)β returns max element(axis = 1[/ 0 for row / [col wise) >>> arr.min(axis = value)β returns min element >>> arr.sum()β returns the sum of all array elements
NumPy Operations
1
2
3
4
5
6
7
8
>>> arr = np.arange(0, 11) >>>
arr + arr # Adding arrays >>>
arrβ arr # Sub arrays >>>
arr * arr # Multiplication arrays >>>
arr + 100 # Adds 100 to every element >>>
arr ** 2 # Exponent operation >>>
np.sqrt(arr) # Square root of arrays >>>
arr1.dot(arr2) # Matrix Multiplication
Link : https://pasteboard.co/IKSTc58.jpg
Indexing and Slicing:
1 2
>>> arr = np.array([(100, 200, 300), (400, 500, 600)]) >>> arr[0](Selects the first row)
[ NOTE :
The value at the right side is for the column.
For row selection the value is before comma.
Column is selected by adding β : β before index.]
1 2
>>> arr[: , 1](Selects second columns) >>> arr[1,: 2](Selects second row with 2 values)
Link : https://pasteboard.co/IKTjdB1.png